package com.visikard.ui.fragment;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.RingUpTask;
import com.visikard.item.ItemGiftKardRedeem;
import com.visikard.ui.R;
import com.visikard.ui.activity.RingUpRedeemActivity;
import com.visikard.utility.BitmapUtils;
import com.visikard.utility.RoundNumber;
import com.visikard.utility.UILImageUtils;

public class RingUpRedeemFragment extends BaseFragment implements ViewClickable {

	public static final String EXT_ITEM_GIFT_KARD = "RingUp_Item_Gift_Kard";

	private ItemGiftKardRedeem mListgiftKards;
	private Context mContext;

	private ImageView imgKard;
	private TextView txtRingUpNameKard;
	private TextView txtPriceKard;
	private EditText edtPriceKard;

	private double mMoneyBuy = 0;
	private double mAmount = 0;
	private double mBalance = 0;

	private BaseTask mAsyncTask;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ringup_giftkard, container, false);

		Bundle bundle = getArguments();
		if (bundle != null) {
			mListgiftKards = (ItemGiftKardRedeem) bundle.getSerializable(EXT_ITEM_GIFT_KARD);
		}
		mContext = getActivity();
		innitControl(view);
		loadData();
		return view;
	}

	private void innitControl(View view) {
		imgKard = (ImageView) view.findViewById(R.id.img_giftkard);
		txtRingUpNameKard = (TextView) view.findViewById(R.id.ringup_namekard);
		txtPriceKard = (TextView) view.findViewById(R.id.ringup_kard_money);
		edtPriceKard = (EditText) view.findViewById(R.id.edt_ringup_monney);
	}

	private void loadData() {
		if (mListgiftKards != null) {

			DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();
			int mWidth = metrics.widthPixels * 3 / 5;
			int mHeight = mWidth * 2 / 3;

			RelativeLayout.LayoutParams lyKard = (RelativeLayout.LayoutParams) imgKard.getLayoutParams();
			lyKard.width = mWidth;
			lyKard.height = mHeight;

			if (mListgiftKards.getIsGiftKard() == 1) {
				// ImageLoader.getInstance(mContext).loadImageCorner(imgKard, mListgiftKards.getImgThumbnail(),
				// 0, BitmapUtils.ROUND_ALL, 4, 3, R.drawable.kard_shadow_default_horizontal, 0, 0);
				UILImageUtils.loadImage(imgKard, // image view
						mListgiftKards.getImgThumbnail(), // url
						0, // size of view
						BitmapUtils.ROUND_ALL, // round all
						4, // round size
						3, // shadow
						R.drawable.kard_shadow_default_horizontal, // shadow resource
						0, 0);
				showKeyboard(true);
			}
			else {
				// ImageLoader.getInstance(mContext).loadImageCorner(imgKard, mListgiftKards.getImgThumbnail(),
				// 0, BitmapUtils.ROUND_NONE, 0, 3, R.drawable.kard_shadow_default_horizontal, 0, 0);
				UILImageUtils.loadImage(imgKard, mListgiftKards.getImgThumbnail(), 0, BitmapUtils.ROUND_NONE, 0, 3,
						R.drawable.kard_shadow_default_horizontal, 0, 0);
				showKeyboard(false);
			}

			// Phuoc: Condition added here
			if (mListgiftKards.getIsGiftKard() == 1
					// partial redeem
					|| mListgiftKards.getCategoryKard() == 2
					|| (mListgiftKards.getCampaignType() == 8 && mListgiftKards.getActiveFunkKard() == 1))
				edtPriceKard.setVisibility(View.VISIBLE);
			else
				edtPriceKard.setVisibility(View.GONE);

			if (mListgiftKards.getMerchantName().length() > 0) {
				txtRingUpNameKard.setVisibility(View.VISIBLE);
				txtRingUpNameKard.setText(mListgiftKards.getMerchantName());
			}
			else
				txtRingUpNameKard.setVisibility(View.GONE);

			if (mListgiftKards.getIsGiftKard() == 1) {
				mMoneyBuy = mListgiftKards.getCert_value();
				txtPriceKard.setText("$" + RoundNumber.roundToSecondDigit(mListgiftKards.getCert_value()));
			}
			// partial redeem
			else if (mListgiftKards.getCategoryKard() == 2
					|| (mListgiftKards.getCampaignType() == 8 && mListgiftKards.getActiveFunkKard() == 1)) {
				mMoneyBuy = RoundNumber.roundToSecondDigit(mListgiftKards.getPurchase_numbervalue());
				txtPriceKard.setText(mListgiftKards.getPurchase_value());
			}
			else {
				mMoneyBuy = 0;
				txtPriceKard.setText(mListgiftKards.getPurchase_value());
			}
			edtPriceKard.requestFocus();
		}
	}

	private boolean checkInputRedeem() {
		double mRedeem = 0;
		// if (mListgiftKards.getIsGiftKard() != 1)
		// return true;

		String text = edtPriceKard.getText().toString().trim();
		if (edtPriceKard.getText().toString().trim().length() <= 0) {
			return false;
		}
		else {
			mRedeem = Double.parseDouble(text);
			if (text.startsWith("."))
				return false;
			else if (mRedeem < 0.01)
				return false;
			else if (mRedeem > mMoneyBuy)
				return false;
		}
		mAmount = Double.parseDouble(edtPriceKard.getText().toString().trim());
		return true;
	}

	@Override
	public void onViewClick(View v) {
		switch (v.getId()) {
			case R.id.accept_redrmption_code:
				showKeyboard(false);
				break;
			case R.id.accept_ringup_code_btn_close:
				showKeyboard(false);
				((RingUpRedeemActivity) getActivity()).finishActivity();
				break;
			case R.id.accept_btn_ringup:
				showKeyboard(false);

				if (VKRegApplication.uid == -1 || VKRegApplication.loginSession == null) {
					Toast.makeText(getActivity(), R.string.login_lost, Toast.LENGTH_LONG).show();
				}
				else {
					// Phuoc: condition added here
					if (mListgiftKards.getIsGiftKard() == 1
							// partial redeem
							|| mListgiftKards.getCategoryKard() == 2
							|| (mListgiftKards.getCampaignType() == 8 && mListgiftKards.getActiveFunkKard() == 1)) {
						if (checkInputRedeem()) {
							mBalance = mMoneyBuy - mAmount;
						}
						else {
							mHandler.sendEmptyMessage(UIMessage.MSG_INPUT_WRONG_PRICE);
							return;
						}
					}
					else {
						mBalance = 0;
					}

					mAsyncTask = new RingUpTask(mHandler);
					mAsyncTask.execute(VKRegApplication.uid, 0L, mListgiftKards.getGiftKardUserId(),
							mListgiftKards.getIdTransaction(), 0L, String.valueOf(mAmount) // redeemed
							, String.valueOf(mMoneyBuy) // previous balance
							, mListgiftKards.getIsGiftKard(), "");
				}
				break;
			default:
				break;
		}
	}

	private void showKeyboard(boolean show) {
		if (show)
			getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
		else
			getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
	}

	@Override
	public boolean handleMessage(Message msg) {
		AlertDialog mDialog;
		switch (msg.what) {
			case UIMessage.MSG_NOT_INPUT_PRICE:
				mDialog = new AlertDialog.Builder(getActivity()).setIcon(android.R.drawable.ic_dialog_info)
						.setMessage(R.string.ringup_input_amount)
						.setPositiveButton(R.string.literal_ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).create();

				mDialog.show();
				return true;
			case UIMessage.MSG_INPUT_WRONG_PRICE:
				mDialog = new AlertDialog.Builder(getActivity()).setIcon(android.R.drawable.ic_dialog_info)
						.setMessage(R.string.ringup_input_wrong_amount)
						.setPositiveButton(R.string.literal_ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).create();
				mDialog.show();
				return true;
			case UIMessage.MSG_RINGUP_SUCCESS:
				showKeyboard(false);
				RingUpSuccessFragment ringUp = new RingUpSuccessFragment();
				Bundle bundle = new Bundle();
				bundle.putDouble(RingUpSuccessFragment.EXT_MONEY_BUY, mMoneyBuy);
				bundle.putDouble(RingUpSuccessFragment.EXT_AMOUNT_REDEEMED, mAmount);
				bundle.putSerializable(EXT_ITEM_GIFT_KARD, mListgiftKards);
				ringUp.setArguments(bundle);
				((RingUpRedeemActivity) getActivity()).putFragment(ringUp);
				return true;
			case UIMessage.MSG_RINGUP_FAILED:
				mDialog = new AlertDialog.Builder(getActivity()).setIcon(android.R.drawable.ic_dialog_info)
						.setMessage(R.string.ringup_failed)
						.setPositiveButton(R.string.literal_ok, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.cancel();
							}
						}).create();
				mDialog.show();
				return true;
		}
		return super.handleMessage(msg);
	}
}
